<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	protected $_id;
	
	/**
	 * @var string email
	 */
	public $email;
	/**
	 * @var string password
	 */
	public $password;

	/**
	 * Constructor.
	 * @param string $username username
	 * @param string $password password
	 */
	public function __construct($email,$password)
	{
		$this->email = $email;
		$this->password = $password;
	}

	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$account = User::model()->findByAttributes(array('email'=>$this->email) );

		if(!isset($account))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		elseif($account->password!== md5($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
			$this->_id = $account->id;
			$this->errorCode=self::ERROR_NONE;

			$this->updateRoles($account);
		}
		return !$this->errorCode;
	}
	
	/**
	 * remove old roles and set new
	 */
	public function updateRoles($account) {
		$this->_id = $account->id;
		
		$auth = Yii::app()->authManager;
		foreach($auth->getAuthAssignments($account->id) as $key=>$assign) {
			$auth->revoke($key, $account->id);
		} 
		
		$auth->assign($account->role, $account->id);
		$auth->save();
	}

	public function getId(){
		return $this->_id;
	}

}